package com.sise.cn.api.common.impl.helper;

import com.sise.cn.api.common.po.BaseUserPO;
import com.sise.cn.constant.RedisConstant;
import com.sise.cn.constant.TimeConstant;
import com.sise.cn.enums.error.SystemError;
import com.sise.cn.exception.SystemException;
import com.sise.cn.redis.cache.RedisUtil;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName LoginHelper
 * @Description
 * @Author CCJ
 * @Date 2020/6/10 14:43
 **/
public class LoginHelper {
    private LoginHelper() {
    }

    public static void validLogin(BaseUserPO baseUserPO, String ip, RedisUtil redisUtil, int failCount, String verifyCode) {
        if (baseUserPO == null) {
            String key = RedisConstant.LOGIN_FAIL_COUNT_KEY.replace("{ip}", ip);
            long count = redisUtil.get(key, Long.class);
            if (count >= failCount) {
                String verifyCodeKey = RedisConstant.LOGIN_VERIFY_CODE.replace("{ip}", ip);
                String redisVerifyCode = redisUtil.get(verifyCodeKey, String.class);
                redisUtil.incrementAndGet(key, 1, TimeConstant.MIN_30_SEN);
                if (StringUtils.isEmpty(verifyCode) || !verifyCode.equalsIgnoreCase(redisVerifyCode)) {
                    throw new SystemException(SystemError.VERIFY_CODE_FAIL);
                }
            }
            redisUtil.incrementAndGet(key, 1, TimeConstant.MIN_30_SEN);
            throw new SystemException(SystemError.USER_NAME_PASSWD_ERROR);
        }
    }

    public static String getRealIP(HttpServletRequest request) {
        String realIp = request.getHeader("X-Real-IP");
        String forwardIp = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(forwardIp)) {
            String[] forwardIpArray = forwardIp.split(",");
            if (0 < forwardIpArray.length) {
                realIp = forwardIpArray[0];
            }
        }
        if (StringUtils.isEmpty(realIp)) {
            realIp = request.getRemoteHost();
        }
        return realIp;
    }
}
